<template>
   <div class="tw-libstar"
    :class="{[`x${this._uid}`]:true}"
    :style="style">
    <el-rate
      v-model="curValue"
      @change="changeScore"
      :disabled-void-color="disabledvoidcolor"
      :disabled="readOnly"
      :show-text="showtext"
      :show-score="showscore"
      :void-color="voidcolor"
      :allow-half="allowhalf"
      :low-threshold="2"
      :max="5"
      :high-threshold="4"
      :text-color="textcolor"
      :texts="text.content"
      :score-template="scoreTpl"
      :colors="colors">
    </el-rate>
   </div>
</template>

<script>
import props from './props'

export default {
  name: 'star',

  props,

  data() {
    return {
      curValue: parseFloat(this.value),
      iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3']
    }
  },

  computed: {
    style () {
      return {
        letterSpacing: this.letterSpacing,
        fontSize: this.fontSize,
        background: this.bgColor
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root.tw-libstar {
          letter-spacing: ${this.letterSpacing};
          background-color: ${this.bgColor};
        }

        ::root.tw-libstar .el-rate__icon {
          margin-right: ${this.letterSpacing};
          font-size: ${this.fontSize};
        }

      `
      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    changeScore (n) {
      if (!this.readOnly) {
        // this.value = n
        this.$emit('input', n)
      }
    }
  },

  mounted () {
    this.setStyle()
  },

  watch: {
    value () {
      this.curValue = parseFloat(this.value)
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
